package com.food.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.food.pojo.Codes;
import com.food.pojo.Users;
import com.food.result.Result;
import com.food.service.UsersService;
import com.food.util.SecurityUtil;
import io.github.classgraph.json.JSONUtils;
import io.minio.MinioClient;
import io.minio.policy.PolicyType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * @author beixiang
 * @version 1.0
 * @description TODO
 * @date 2023/4/11 14:57
 */
@Api(tags = "用户登录接口")
@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "*")
public class UsersController {

    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.fileBucketName}")
    private String fileBucketName;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secretKey}")
    private String secretKey;

    @Autowired
    UsersService usersService;

    @ApiOperation(value = "获得token")
    @PostMapping("/getUserToken")
    public Result getUserToken(@RequestParam("code") String code) {
        String token=usersService.getUserToken(code);
        return Result.ok(token);
    }

    @ApiOperation(value = "获得用户信息")
    @PostMapping("/getUsers")
    public Result getUsers() {
        SecurityUtil.Users user = SecurityUtil.getUser();
        Integer userId = user.getUserId();
        Users users = usersService.getUsers(userId);
        users.setOpenid(null);
        users.setUserPassword(null);
        return Result.ok(users);
    }

//    @ApiOperation(value = "获得用户信息")
//    @PostMapping("/getUsers")
//    public Result getUsers(@RequestParam("userId") Integer userId) {
//        Users users = usersService.getUsers(userId);
//        return Result.ok(users);
//    }

    @ApiOperation(value = "修改用户信息")
    @PostMapping("/updataUsers")
    public Result updataUsers(@RequestParam("userId") Integer userId,
                              @RequestParam("userName") String userName,
                              @RequestParam("userSex") String userSex,
                              @RequestParam("userIntroduce") String userIntroduce,
                              @RequestParam("userAvatar") String userAvatar,
                              @RequestParam("userBackground") String userBackground) {

        Boolean bool= usersService.updataUsers(userId,userName,userSex,userIntroduce,userAvatar,userBackground);
        if(bool){
            return Result.ok();
        }else {
            return Result.fail("修改失败");
        }
    }

    @RequestMapping(value = "/file", method = RequestMethod.POST)
    public Result uploadFile(@RequestPart("file") MultipartFile file,@RequestParam("userId") Integer userId,@RequestParam("type") String type) {
        if (file == null) {
            System.out.println("出错");
           return Result.fail("没有数据");

        }
        System.out.println(type);
        try {

            MinioClient minioClient = getMinioClient(fileBucketName);
//            String objectName = getFileName(file);
            String objectName =type+userId+".jpg";
            // 使用putObject上传一个文件到存储桶中。
            minioClient.putObject(fileBucketName, objectName, file.getInputStream(), file.getContentType());

            //  可以在浏览器上直接访问的地址
            //  在这里要注意的是，刚上传时，图片是不能直接访问的，要去minio服务器中，添加对应的桶的权限，然后重启minio服务器
            //  点击桶右边的三个点 -> Edit policy -> ADD -> Read and Write -> 重启minio 服务器
            String objectUrl = minioClient.getObjectUrl(fileBucketName, objectName);
            System.out.println(objectUrl);
            return Result.ok(objectUrl);
        } catch(Exception e) {
//            return ResultUtil.fail(ResultEnum.FAIL_FILE_UPLOAD);
            System.out.println("出错");
            return Result.fail("出错");

        }
    }

    /**
     * 获取 minio 的链接
     * @return  minio链接
     * @throws Exception
     */
    private MinioClient getMinioClient(String bucketName) throws Exception {
        // 使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
        MinioClient minioClient = new MinioClient(endpoint, accessKey, secretKey);

        // 检查存储桶是否已经存在
        boolean isExist = minioClient.bucketExists(bucketName);
        if(!isExist) {
            // 创建一个名为 bucketName 的存储桶
            minioClient.makeBucket(bucketName);
            minioClient.setBucketPolicy(bucketName, ".", PolicyType.READ_ONLY);
        }
        return minioClient;
    }


}
